package com.xinhe.web.service;

import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.xinhe.web.common.Result;
import com.xinhe.web.entity.*;
import com.xinhe.web.reposity.GoodsPriceRepository;
import com.xinhe.web.request.GoodsPriceModel;
import com.xinhe.web.util.Snowflake;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.inject.Provider;
import javax.persistence.EntityManager;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service

public class GoodsPriceService {
    @Autowired
    private GoodsPriceRepository goodsPriceRepository;
    //查询工厂
    private JPAQueryFactory queryFactory;
    @Autowired
    private Provider<EntityManager> entityManager;
    @PostConstruct
    public void init() {
        queryFactory = new JPAQueryFactory(entityManager);
    }

    public Result<List<GoodsPrice>> findGoodsPrice(Long goodsId) {
        List<GoodsPrice> goodsPrices = this.goodsPriceRepository.findGoodsPrice(goodsId);
        return Result.ok(goodsPrices);
    }
    @Transactional(rollbackFor = Exception.class)
    public void saveGoodsPrice(List<GoodsPriceModel> goodsPriceList, Goods goods) {
        List<GoodsPrice> goodsPrices = this.goodsPriceRepository.findGoodsPrice(goods.getId());
        Map<Long, GoodsPrice> map = new HashMap<>();
        if (CollectionUtils.isNotEmpty(goodsPrices)) {
            map = (Map<Long, GoodsPrice>)goodsPrices.stream().collect(Collectors.toMap(GoodsPrice::getId, goodsPrice -> goodsPrice));
        }
        for (int i = 0; i < goodsPriceList.size(); i++) {
            GoodsPriceModel goodsPriceModel = goodsPriceList.get(i);
            goodsPriceModel.setGoodsId(goods.getId());

            GoodsPrice gp= new GoodsPrice();
            BeanUtils.copyProperties(goodsPriceModel, gp);
            gp.setId(Snowflake.generateId());
            GoodsPrice item = goodsPriceRepository.save(gp);
            GoodsPrice goodsPrice = map.get(goodsPriceModel.getId());
            if (goodsPrice != null) {
                map.remove(goodsPriceModel.getId());
            }
            if (i == 0) {
                goods.setPrice(goodsPriceModel.getPrice());
                goods.setPriceId(item.getId());
                goods.setSpikePrice(item.getSeckillPrice());
                goods.setGroupPurchasePrice(item.getGroupPurchasePrice());
            }
        }
        if (map.keySet().size() > 0) {
            this.goodsPriceRepository.deleteByIdIn(map.values().stream().map(GoodsPrice::getId).collect(Collectors.toSet()));
        }
    }

    public QueryResults<GoodsPrice> pageGoodsPrice(Long goodsId, String name, int pageNum, int pageSize) {
        QGoodsPrice qGoodsPrice = QGoodsPrice.goodsPrice;
        BooleanBuilder builder = new BooleanBuilder();
        if (!Objects.isNull(goodsId)) {
            builder.and(qGoodsPrice.goodsId.eq(goodsId));
        }
        if (!Objects.isNull(name)) {
            builder.and(qGoodsPrice.name.eq(name));
        }
        return queryFactory.select(
                        Projections.bean(
                                GoodsPrice.class,
                                qGoodsPrice.id,
                                qGoodsPrice.name,
                                qGoodsPrice.goodsId,
                                qGoodsPrice.originalPrice,
                                qGoodsPrice.unit,
                                qGoodsPrice.groupPurchasePrice,
                                qGoodsPrice.seckillPrice
                        )
                ).from(qGoodsPrice)
                .where(builder).offset(pageNum * pageSize).limit(pageSize).fetchResults();
    }


    public Result saveModel(GoodsPriceModel model) {
        GoodsPrice goodsPrice = new GoodsPrice();
        BeanUtils.copyProperties(model, goodsPrice);
        goodsPriceRepository.save(goodsPrice);
        return Result.ok();
    }

    public Result delete(Long goodsPriceId) {
        goodsPriceRepository.deleteById(goodsPriceId);
        return Result.ok();
    }

    public Result findById(Long goodsPriceId) {
        return Result.ok(goodsPriceRepository.findById(goodsPriceId).get());
    }
}
